﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace RobotBattle2.Utilities {
	public static class StringUtils {
		static readonly Regex NeedsEscape = new Regex("[\n\t\r\\\\]");

		public static string ApplyFormat(this string format, params object[] args) {
			return string.Format(format, args);
		}

		public static string Escape(this string input) {
			if (!NeedsEscape.IsMatch(input))
				return input;
			var result = new StringBuilder(input.Length + 32);
			foreach (char ch in input) {
				switch (ch) {
					case '\\': result.Append("\\\\"); break;
					case '\t': result.Append("\\t"); break;
					case '\r': result.Append("\\r"); break;
					case '\n': result.Append("\\n"); break;
					default:
						result.Append(ch);
						break;
				}
			}
			return result.ToString();
		}

		public static string Unescape(this string input) {
			var result = new StringBuilder(input.Length + 32);
			bool unescapeNext = false;
			foreach (char ch in input) {
				if (ch == '\\')
					unescapeNext = true;
				if (unescapeNext) {
					unescapeNext = false;
					switch (ch) {
						case 't': result.Append("\t"); break;
						case 'r': result.Append("\r"); break;
						case 'n': result.Append("\n"); break;
						default:
							result.Append(ch);
							break;
					}
				} else {
					result.Append(ch);
				}
			}
			return result.ToString();
		}
	}
}
